package com.example.hrandroidapp.fragment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lib.jason.requestresponsetask.HTTPUtils;
import lib.jason.requestresponsetask.JSONHTTPPoster;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

import com.dobmob.doblist.DobList;
import com.dobmob.doblist.events.OnLoadMoreListener;
import com.dobmob.doblist.exceptions.NoEmptyViewException;
import com.dobmob.doblist.exceptions.NoListViewException;
import com.example.hrandroidapp.LeaveMailDetailActivity;
import com.example.hrandroidapp.R;
import com.example.hrandroidapp.adapter.LeaveApprovalAdapter;
import com.example.hrandroidapp.common.Constant;
import com.example.hrandroidapp.common.DateUtils;
import com.example.hrandroidapp.common.HRLog;
import com.example.hrandroidapp.domain.LeavePO;
import com.example.hrandroidapp.preferences.CurrentServerPreference;
import com.example.hrandroidapp.preferences.UserPreference;

public class MyLeaveFragment extends Fragment implements LeaveApprovalAdapter.AcceptCallBack {

	private ListView lstLeaveAproval;
	private LeaveApprovalAdapter leaveApprovAdpt;
	private MyLeaveFragment fragment=this;
	private List<LeavePO> lstLeaves;
	private String url;
	private DobList dobList;
	
	private final String MY_LEAVE_STATUS = "1";
	private String lastLeaveId = "0";
	private boolean myLeave = true;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_my_leave, container, false);
		
		loadViews(rootView);
		loadLeaves();
		
		 // hard code
//	    for(int i=0; i<10; i++) {
//	    	LeavePO leavePO = new LeavePO();
//	    	leavePO.setEmployeeName("Name "+i);
//	    	leavePO.setLeaveDescription("Reject Message " + i);
//	    	Date currentDate = new Date();
//	    	leavePO.setCreatedDate("20150112");
//	    	
//	    	lstLeaves.add(leavePO);
//	    }

		
	    lstLeaveAproval.setAdapter(leaveApprovAdpt);
	    leaveApprovAdpt.setCheckableListView(false);
	    
	    lstLeaveAproval.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				LeavePO leavePO = lstLeaves.get(position); 
				Intent intent = new Intent(fragment.getActivity().getApplicationContext(), LeaveMailDetailActivity.class);
				intent.putExtra("leave", leavePO); 
				intent.putExtra("pending", "0");
				getActivity().startActivity(intent); 
			}
		});
		return rootView;
	}
	
	private void loadViews(View rootView) {
		lstLeaveAproval = (ListView) rootView.findViewById(R.id.list_my_leave);
		lstLeaves = new ArrayList<LeavePO>();
		leaveApprovAdpt = new LeaveApprovalAdapter(fragment.getActivity().getApplicationContext(), lstLeaves, this);
	    initDobList(rootView, lstLeaveAproval);
	}

	private void loadLeaves() {

		if(isAdded()) {
			url = getResources().getString(R.string.leave_url);
			String completeUrl = "http://" + CurrentServerPreference.getCurrentServer(getActivity()).getSvrIP() + ":" + Constant.PORT + url;
			
			HRLog.postLogInfo("leave reject url complete: " + completeUrl, "LeavePendingFragment.loadLeaves"); 
			new HTTPUtils(getActivity(), JSONHTTPPoster.MEDIA_FORM_URLENCODED, completeUrl, populateRequestParameterMap(), 
					new HTTPUtils.SimpleRequestResponseTaskInterface() {
	
				@Override
				public void handleResponse(String responseStr, int status) throws Exception {
					HRLog.postLogDebug("JSON string: " + responseStr, "LeavePendingFragment.onCreateView");
					
					JSONArray jsonArray = new JSONArray(responseStr);
					lstLeaves.clear();
					for (int i = 0; i < jsonArray.length(); i++) {
	
		                JSONObject jsonobject = jsonArray.getJSONObject(i);
		                LeavePO leavePO = new LeavePO();
		                
		                leavePO.setColor(jsonobject.getString("color"));
		                String createdDate = jsonobject.getString("createdDate");
		                leavePO.setCreatedDate(createdDate); 
		                leavePO.setEmployeeName(jsonobject.getString("employeeName"));
		                
		                createdDate = jsonobject.getString("endDateTime");
		                leavePO.setEndDateTime(createdDate); 
		                leavePO.setLeaveDescription(jsonobject.getString("leaveDescription"));
		                leavePO.setLeaveId(Long.parseLong(jsonobject.getString("leaveId")));
		                
		                createdDate = jsonobject.getString("startDateTime");
		                leavePO.setStartDateTime(createdDate); 
		                leavePO.setReason(jsonobject.getString("subject"));
		                leavePO.setTotalDays(Double.parseDouble(jsonobject.getString("totalDays")));
		                lstLeaves.add(leavePO); 
		           }
					
					Collections.sort(lstLeaves, new Comparator<LeavePO>() {
	
						@Override
						public int compare(LeavePO obj1, LeavePO obj2) {
							return obj1.getCreatedDate().compareTo(obj2.getCreatedDate());
						}
					});
					
					leaveApprovAdpt = new LeaveApprovalAdapter(fragment.getActivity().getApplicationContext(), lstLeaves, fragment);
				    lstLeaveAproval.setAdapter(leaveApprovAdpt);
				    
				}
				
			}).execute();
		}
		
	}

	public Map<String, String> populateRequestParameterMap() {
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("leaveStatus", MY_LEAVE_STATUS);
		paramMap.put("leaveId", lastLeaveId);
		paramMap.put("loginId", UserPreference.getLoginId(getActivity()));
		paramMap.put("size", String.valueOf(Constant.LEAVE_SIZE));
		paramMap.put("myLeave", String.valueOf(myLeave));
		
		return paramMap;
	}
	
	private void initDobList(View rootView, ListView listView) {

		dobList = new DobList();
		try {

			dobList.register(listView);

			dobList.addDefaultLoadingFooterView();

			// Sets the view to show if the adapter is empty
			// see startCentralLoading() method
			View noItems = rootView.findViewById(R.id.no_my_leave_items);
			dobList.setEmptyView(noItems);

			// Callback called when reaching last item in ListView
			dobList.setOnLoadMoreListener(new OnLoadMoreListener() {

				@Override
				public void onLoadMore(final int totalItemCount) {

					// Just inserting some dummy data after
					// period of time to simulate waiting
					// data from server
					loadMoreData(10);
				}
			});

		} catch (NoListViewException e) {
			e.printStackTrace();
		}

		try {
			// Show ProgressBar at the center of ListView
			// this can be used while loading data from
			// server at the first time
			//
			// setEmptyView() must be called before
			//
			// NoEmptyViewException will be thrown when
			// there is no EmptyView
			dobList.startCentralLoading();

		} catch (NoEmptyViewException e) {
			e.printStackTrace();
		}
		// Simulate adding data at the first time
		loadMoreData(20);
	}

	protected void loadMoreData(final int itemsCount) {
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				addItems(leaveApprovAdpt.getCount(), leaveApprovAdpt.getCount() + itemsCount);

				// We must call finishLoading
				// when finishing adding data
				dobList.finishLoading();
			}

		}, 3000);
	}

	protected void addItems(int from, int to) {
//		for(int i=from; i<to; i++) {
//	    	LeavePO leavePO = new LeavePO();
//	    	leavePO.setEmployeeName("Name "+i);
//	    	leavePO.setLeaveDescription("Pending Message " + i);
//	    	Date currentDate = new Date();
//	    	leavePO.setCreatedDate(DateUtils.convert(currentDate, DateUtils.DATE_DDMMYYYY_FORMAT));
//	    	
//	    	leaveApprovAdpt.addLeave(leavePO);
//	    }
	}

	@Override
	public void setAccptVisible(boolean flag) {}

}
